package com.panicstyle.Gongdong;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlSerializer;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class ArticleModify extends Activity implements Runnable {
	protected HttpClient httpClient;
	protected HttpContext httpContext;
    private ProgressDialog pd;
    private String mTitle;
    private String mContent;
    private String mCommID;
    private String mBoardID;
    private String mBoardNo;
    private boolean bSaveStatus;
    private String mErrorMsg;

	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.article_write);    

        GongdongApplication app = (GongdongApplication)getApplication();
        httpClient = app.httpClient;
        httpContext = app.httpContext;

        intenter();
        
        mContent = mContent.replaceAll("\n", "");
        mContent = mContent.replaceAll("\r", "");
        mContent = mContent.replaceAll("<br>", "\n");
        mContent = mContent.replaceAll("&nbsp;", " ");
        mContent = mContent.replaceAll("(<style)(.|\\n)*?(</style>)", "");
        mContent = mContent.replaceAll("(<)(.|\\n)*?(>)", "");
        mContent = mContent.trim();
        
        findViewById(R.id.okbtn).setOnClickListener(mClickListener);
        findViewById(R.id.cancelbtn).setOnClickListener(mClickListener);
        
		EditText tTitle = (EditText)findViewById(R.id.editTitle); 
		tTitle.setText(mTitle);
		EditText tContent = (EditText)findViewById(R.id.editContent); 
		tContent.setText(mContent);
    }

    public void intenter() {
//    	Intent intent = getIntent();  // 값을 가져오는 인텐트 객체생성
    	Bundle extras = getIntent().getExtras();
    	// 가져온 값을 set해주는 부분
    	mCommID = extras.getString("COMMID").toString();
    	mBoardID = extras.getString("BOARDID").toString();
    	mBoardNo = extras.getString("BOARDNO").toString();
    	mTitle = extras.getString("TITLE").toString();
    	mContent = extras.getString("CONTENT").toString();
    }
    
    public void SaveData() {
    	
    	EditText textTitle = (EditText)findViewById(R.id.editTitle);
    	EditText textContent = (EditText)findViewById(R.id.editContent);

    	mTitle = textTitle.getText().toString();    	
    	mContent = textContent.getText().toString();
    	
    	if (mTitle.length() <= 0 || mContent.length() <= 0) {
    		AlertDialog.Builder ab = null;
			ab = new AlertDialog.Builder( this );
			ab.setMessage( "입력된 내용이 없습니다. 종료하시겠습니까?");
			ab.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					finish();
				}
			});
			ab.setPositiveButton(android.R.string.cancel, null);
			ab.setTitle( "확인" );
			ab.show();
			return;
    	}
    	
        pd = ProgressDialog.show(this, "", "저장중입니다. 잠시만 기다리십시오...", true, false);

        Thread thread = new Thread(this);
        thread.start();

        return;
    }

    public void run() {
   		PostData(httpClient, httpContext);
    	handler.sendEmptyMessage(0);
    }

    private Handler handler = new Handler() {
    	@Override
    	public void handleMessage(Message msg) {
    		pd.dismiss();
    		if (!bSaveStatus) {
	    		AlertDialog.Builder ab = null;
				ab = new AlertDialog.Builder( ArticleModify.this );
				String strErrorMsg = "글 저장중 오류가 발생했습니다. \n" + mErrorMsg; 
				ab.setMessage(strErrorMsg);
				ab.setPositiveButton(android.R.string.ok, null);
				ab.setTitle( "확인" );
				ab.show();
				return;
    		}
            finish();
    	}
    };        
    	
    protected boolean PostData(HttpClient httpClient, HttpContext httpContext) {
		HttpRequest httpRequest = new HttpRequest();
		
		String url = "http://cafe.gongdong.or.kr/cafe.php?mode=edit&p2=&p1=" + mCommID + "&sort=" + mBoardID;
/*
        mContent = mContent.replaceFirst("\n", "<div>");
        mContent = mContent.replaceAll("\n", "</div><div>");
        mContent = mContent + "</div>";
*/
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("number", mBoardNo));
		nameValuePairs.add(new BasicNameValuePair("usetag", "n"));
		nameValuePairs.add(new BasicNameValuePair("subject", mTitle));
		nameValuePairs.add(new BasicNameValuePair("content", mContent));
		
		String result = httpRequest.requestPost(httpClient, httpContext, url, nameValuePairs, "", "utf-8");

        if (result.indexOf("<meta http-equiv=\"refresh\" content=\"0;url=/cafe.php?sort=") < 0) {
            Pattern p = Pattern.compile("(?<=window.alert\\(\\\")(.|\\n)*?(?=\\\")", Pattern.CASE_INSENSITIVE); 
            Matcher m = p.matcher(result);
            
            if (m.find()) { // Find each match in turn; String can't do this.     
            	mErrorMsg = m.group(0);
            } else {
            	mErrorMsg = "";
            }
			bSaveStatus = false;
			return false;
        }
        
		bSaveStatus = true;
    	return true;
    }
    	
    public void CancelData() {
    	finish();
    }
    
    Button.OnClickListener mClickListener = new View.OnClickListener()
    {
      public void onClick(View v)
      {
          switch (v.getId())
          {
          case R.id.okbtn:
               if (getParent() == null) {
               	setResult(Activity.RESULT_OK, new Intent());
               } else {
               	getParent().setResult(Activity.RESULT_OK, new Intent());
               }
               SaveData();
               break;
          case R.id.cancelbtn:
               if (getParent() == null) {
               	setResult(Activity.RESULT_CANCELED, new Intent());
               } else {
               	getParent().setResult(Activity.RESULT_CANCELED, new Intent());
               }
               CancelData();
               break;
          }
      }
    };
}
